import React, { useState } from 'react'
import { getTrainApi } from '../api/user'
import { useLoaderData, useSearchParams } from 'react-router-dom'
import { InfiniteScroll } from 'antd-mobile'
import Item from '../componst/Item'
import styles from '../css/Item.module.css'
import { Collapse } from 'antd-mobile'
import useAunt from '../hooks/useAunt'
function Listt() {
  let {isLogin} = useAunt()

  let loaderData = useLoaderData()
  let [list, setList] = useState(loaderData.list)
  const [hasMore, setHasMore] = useState(true)
  let [page, setPage] = useState(1)
  let [sp] = useSearchParams()
  async function loadMore() {
    setPage((k) => k + 1)
    let obj = { ...Object.fromEntries(sp), page: page + 1 }
    let { data: res } = await getTrainApi(obj)
    setList([...list, ...res])
    if (res.length === 0) {
      setHasMore(false)
    }
  }
  return (
    <div>
      <div className={styles.top}>{list[0].startStation}-{list[0].endStation}</div>
      <Collapse defaultActiveKey={['1']}>
        <Collapse.Panel key='1' title='以下为普通列车'>
          {
            list && list.map((item) => {
              return <Item key={item.id} {...item} />
            })
          }
        </Collapse.Panel>
      </Collapse>

      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}

export default Listt
export const loader = async ({ request }) => {
  let url = new URL(request.url)
  let obj = { ...Object.fromEntries(url.searchParams) }
  let { data: res } = await getTrainApi(obj)
  console.log(res);
  return { list: res }
}